package persistencia;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dominio.*;

public class AutorDAO {

	public static Autor newAutor(String nif) throws Exception {
		Autor result=null;
		result = new Autor();
		String SQL="Select Persona.dni, nombre, apellido, afiliación, email from Persona,Autor where Persona.dni=Autor.dni and Persona.dni=?";
		Conexion bd=null;
		Exception ex=null;
		PreparedStatement p=null;
		try {
				bd = Broker.get().getBD();
				p = bd.prepareStatement(SQL);
				p.setString(1, nif);
				ResultSet r = p.executeQuery();
				if (r.next()) {
					result.setDni(r.getString(1));
					result.setNombre(r.getString(2));
					result.setApellido(r.getString(3));
					result.setAfiliacion(r.getString(4));
					result.setEmail(r.getString(5));
				} else {
					throw new Exception("La persona con NIF " + nif + " no existe");
				}			
		} catch (Exception e) {
			ex = e;
	}
		finally {
			bd.close();
			if (ex!=null)
				throw ex;
		}
		return result;
	}
	
	

	public static void insert(Autor autor) throws Exception{
		PersonaDAO.insert(autor);
		String SQL="Insert into Autor (dni) values (?)";
		Conexion bd=null;
		Exception ex=null;
		PreparedStatement p=null;
		try {
			bd=Broker.get().getBD();
			p=bd.prepareStatement(SQL);
			p.setString(1, autor.getDni());
			p.executeUpdate();
		}
		catch (Exception e) {
			ex=e;
		}
		finally {
			bd.close();
			if (ex!=null)
				throw ex;
		}
	}
	
	public static void delete(Autor autor) throws Exception {
		PersonaDAO.delete(autor);
	}
	
}
